package com.karry.yl.service.system.impl;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.karry.commons.base.impl.SuperServiceImpl;
import com.karry.yl.dao.system.UserMapper;
import com.karry.yl.domain.baseinfo.Enterprise;
import com.karry.yl.domain.baseinfo.MinfeiUnits;
import com.karry.yl.domain.baseinfo.Organization;
import com.karry.yl.domain.system.User;
import com.karry.yl.service.baseinfo.EnterpriseService;
import com.karry.yl.service.baseinfo.MinfeiUnitsService;
import com.karry.yl.service.baseinfo.OrganizationService;
import com.karry.yl.service.system.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class UserServiceImpl extends SuperServiceImpl<UserMapper,User> implements UserService{

    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private MinfeiUnitsService minfeiUnitsService;

    @Override
    public Page<User> selectUserPage(Page<User> page, Long orgId,Wrapper<User> var2) {
        return page.setRecords(baseMapper.selectUserList(page,orgId, var2));
    }

    @Override
    public void update(User user) {
        baseMapper.update(user);
    }

    @Override
    public void modifyStatus(Long id) {
        baseMapper.modifyStatus(id);
    }

    @Override
    public void modifyRole(Long id, Long roleId) {
        baseMapper.modifyRole(id,roleId);
    }

    @Override
    @Transactional
    public void regist(User user,Organization org, Enterprise enterprise, MinfeiUnits minfeiUnits) {
        if(org.getType() == Organization.TYPE_LS){ //关联企业
            if(enterprise.getId() == null){
                enterpriseService.insert(enterprise);
            }
            org.setEnterpriseId(enterprise.getId());
            org.setEnterpriseName(enterprise.getName());
        }else if(org.getType() == Organization.TYPE_MF){ //关联民非
            if(minfeiUnits.getId() == null){
                minfeiUnitsService.insert(minfeiUnits);
            }
            org.setMinfeiUnitsId(minfeiUnits.getId());
            org.setMinfeiUnitsName(minfeiUnits.getName());
        }
        org.setStar(0);//未备案
        org.setFilingStart(0);
        org.setPrimary(false); //是否主机构
        //创建机构
        organizationService.insert(org);
        //生成用户
        user.setOrgId(org.getId());
        user.setRoleId(1L);//机构默认的角色ID
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        user.setPrimary(true);
        user.setStatus(User.STATUS_ACTIVE);
        user.setUserName(user.getPhone());
        super.baseMapper.insert(user);
    }
}
